package cn.wynu.controller;

import cn.wynu.order.bean.Order;
import cn.wynu.product.bean.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/order")
@Slf4j
@RefreshScope
public class OrderController {
    @Autowired
    DiscoveryClient discoveryClient;

    @Autowired
    LoadBalancerClient loadBalancerClient;

    @Autowired
    RestTemplate restTemplate;

    @Value("${zhangsan.name}")
    String name;
    @Value("${zhangsan.age}")
    Integer age;

    @GetMapping("/zhangsan")
    public String getZhangsan() {
        return name + age;
    }

    @PostMapping
    public Order addOrder(@RequestParam("userId") Long userId,
                           @RequestParam("productId")Long productId) {
        Order order = new Order();
        order.setOrderId(1L);

        Product product = getProduct(productId);
        Integer num = product.getNum();
        order.setTotalAmount(product.getProductPrice().multiply(BigDecimal.valueOf(num)));

        order.setUserId(userId);
        order.setNickName("");
        order.setAddress("");

        List<Product> products = Arrays.asList(product);
        order.setProductList(products);

        return order;
    }

    /**
     * 远程调用商品接口，可复用
     * 每次使用的服务实例都是同一个，没有实现负载均衡
     * @param productId 商品id
     * @return 商品详情
     */
    Product getProduct(Long productId) {
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance serviceInstance = instances.get(0);

        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();

        String url = String.format("http://%s:%d/product/%s", host, port, productId);
        log.info("远程实例信息：{}", url);
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }


    @PostMapping("/balance")
    public Order addOrderBalance(@RequestParam("userId") Long userId,
                          @RequestParam("productId")Long productId) {
        Order order = new Order();
        order.setOrderId(1L);

        Product product = getProductBalance(productId);
        Integer num = product.getNum();
        order.setTotalAmount(product.getProductPrice().multiply(BigDecimal.valueOf(num)));

        order.setUserId(userId);
        order.setNickName("");
        order.setAddress("");

        List<Product> products = Arrays.asList(product);
        order.setProductList(products);

        return order;
    }

    /**
     * 远程调用商品接口，可复用
     * 负载均衡方法获取服务实例，每次获取到的服务实例不是同一个
     * @param productId 商品id
     * @return 商品详情
     */
    Product getProductBalance(Long productId) {
        ServiceInstance serviceInstance = loadBalancerClient.choose("service-product");
        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();

        String url = String.format("http://%s:%d/product/%s", host, port, productId);
        log.info("远程实例信息：{}", url);
        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }

    @PostMapping("/balance/annotation")
    public Order addOrderBalanceAnnotation(@RequestParam("userId") Long userId,
                                 @RequestParam("productId")Long productId) {
        Order order = new Order();
        order.setOrderId(1L);

        Product product = getProductBalanceAnnotation(productId);

        Integer num = product.getNum();
        order.setTotalAmount(product.getProductPrice().multiply(BigDecimal.valueOf(num)));

        order.setUserId(userId);
        order.setNickName("");
        order.setAddress("");

        List<Product> products = Arrays.asList(product);
        order.setProductList(products);

        return order;
    }

    /**
     * 远程调用商品接口，可复用
     * 负载均衡方法获取服务实例，每次获取到的服务实例不是同一个
     * @param productId 商品id
     * @return 商品详情
     */
    Product getProductBalanceAnnotation(Long productId) {

        String url = String.format("http://service-product/product/%s", productId);
        return restTemplate.getForObject(url, Product.class);
    }

}
